package com.ahmedmisbah.andgenplus.utils.android;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import com.ahmedmisbah.andgenplus.constants.GlobalConstants;
import com.ahmedmisbah.andgenplus.utils.android.exception.AndroidManifestUtilException;
import com.ahmedmisbah.andgenplus.utils.pde.PDEUtil;
import com.ahmedmisbah.andgenplus.utils.xml.XMLUtil;

public class AndroidManifestUtil extends XMLUtil {

	public static final String INTERNET_PERMISSION = "android.permission.INTERNET";
	private Document androidManifestDocument;
	private Element root;

	public AndroidManifestUtil() {
		try {
			this.androidManifestDocument = getDocument(getAndroidManifestFilePath());
			this.root = androidManifestDocument.getRootElement();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String getAndroidManifestFilePath()
	{
		return PDEUtil.getEclipseProject().getLocation().toString()
				+ File.separator + GlobalConstants.ANDROID_MANIFEST;
	}


	public void insertPermission(String permission) {
		Element testElement = getElement(root, "./uses-permission[@android:name='"+permission+"']", true);

		if (testElement == null) {
			root.addElement("uses-permission").addAttribute("android:name",
					permission);
		}

	}

	public void insertActivity(String activityFullClassPath) {
		Element applicationElement = getElement(root, "application", false);
		Element testElement = getElement(applicationElement, "./activity[@android:name='"+activityFullClassPath+"']", true);

		if (testElement == null) {
			applicationElement.addElement("activity").addAttribute(
					"android:name", activityFullClassPath);
		}

	}

	public void commitChanges() throws AndroidManifestUtilException {
		// lets write to a file
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileWriter(
					getAndroidManifestFilePath()));

			writer.write(androidManifestDocument);
			writer.close();

		} catch (IOException e) {
			throw new AndroidManifestUtilException(e);
		}
	}

}
